//
//  WSAnswerChildViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/10/23.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSAnswerChildViewController.h"
#import "WSQuestionDetailViewController.h"
#import "WSAnswerTableCell.h"
#import "YZDisplayViewHeader.h"

#import "QAService.h"
#import "QuestionInfo.h"

static NSString *cellID = @"WSAnswerTableCell";

@interface WSAnswerChildViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) NSArray <QuestionInfo *> *datas;

@property (nonatomic, assign) NSInteger pageNo; // 分页
// 搜索关键字
@property (nonatomic, copy) NSString *keywords;

@end

@implementation WSAnswerChildViewController

#pragma mark - Life Cycle
- (void)dealloc {
    [kNotificationCenter removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self ws_addSubviews];
    [self ws_setup];
    [self addNotificationCenter];
}

#pragma mark - Override

- (void)ws_addSubviews {
    [self.view addSubview:self.tableView];
}

- (void)ws_setup {
    self.pageNo = 1;
    WEAKSELF
    [self.tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
        [weakSelf ws_loadData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

/**
 加载分类数据
 */
- (void)ws_loadData {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = User_Token;
    dic[@"cate_id"] = _cateId;
    if (!STR_Is_NullOrEmpty(self.keywords)) {
        dic[@"keywords"] = self.keywords;
    }
    dic[@"page"] = @(self.pageNo);
    [QAService fetchAskListWithParams:dic result:^(id object) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:object];
        if (!response.data) {
            return;
        }
        self.datas = [NSArray yy_modelArrayWithClass:[QuestionInfo class] json:response.data[@"data"]];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)addNotificationCenter {
    // 监听滚动完成或者点击标题，只要滚动完成，当前控制器就会发出通知
    // 只需要监听自己发出的，不需要监听所有对象发出的通知，否则会导致一个控制器发出，所有控制器都能监听,造成所有控制器请求数据
    [kNotificationCenter addObserver:self selector:@selector(loadPage:) name:YZDisplayViewClickOrScrollDidFinshNote object:self];
    
    [kNotificationCenter addObserver:self selector:@selector(doSearch:) name:@"SearchNotification" object:nil];
}

- (void)loadMoreData {
    WEAKSELF
    [self.tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
        weakSelf.pageNo += 1;
        
    }];
}

#pragma mark - Notification

// load page data
- (void)loadPage:(NSNotification *)noti {
    if ([noti.object isKindOfClass:[self class]]) {
        WSAnswerChildViewController *vc = noti.object;
        if (vc.isLoad) return; // 已经加载过，就不需要再次加载
        vc.isLoad = YES;
        // load page data
        [self ws_loadData];
    }
}

// do search...
- (void)doSearch:(NSNotification *)noti {
    self.keywords = noti.object;
    [self ws_loadData];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSAnswerTableCell *cell = (WSAnswerTableCell *)[tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.questions = self.datas[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WSTeacher" bundle:nil];
    WSQuestionDetailViewController *detailVc = [storyboard instantiateViewControllerWithIdentifier:[WSQuestionDetailViewController className]];
    detailVc.ask_id = self.datas[indexPath.section].ask_id;
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return section == 0 ? self.headerView : [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? 44.f : 0.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

#pragma mark - Getter

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10.f, self.view.xmg_width, self.view.xmg_height-44.f-kTabBarHeight-_yOffset-10.f) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kCommonBackgroudColor;
        _tableView.separatorColor = kSeparatorColor;
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.estimatedRowHeight = 175.f;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WSAnswerTableCell class]) bundle:nil] forCellReuseIdentifier:cellID];
    }
    return _tableView;
}

- (UIView *)headerView {
    if (_headerView == nil) {
        _headerView = [UIView new];
        _headerView.backgroundColor = [UIColor whiteColor];
        [_headerView setBorder:kSeparatorColor borderWidth:1.f borderType:UIBorderSideTypeBottom];
        
        UIView *greenLine = [UIView new];
        greenLine.backgroundColor = kThemeGreenColor;
        greenLine.layer.cornerRadius = 1.f;
        [_headerView addSubview:greenLine];
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = @"热门问答";
        titleLabel.textColor = COLOR_HEX(0x191919);
        titleLabel.font = WSFontMake(15);
        [_headerView addSubview:titleLabel];
        
        [greenLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(11.f);
            make.centerY.offset(0.f);
            make.size.mas_equalTo(CGSizeMake(3.f, 18.f));
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(greenLine).offset(10.f);
            make.centerY.offset(0.f);
        }];
    }
    return _headerView;
}

- (IBAction)inputText:(id)sender {
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
